#include "util/threads.h"
#include "util/TimeEx.h"

qcutil::CThreadBase::CThreadBase()
{
    m_thread = 0;
}

qcutil::CThreadBase::~CThreadBase()
{
    close();
}

bool qcutil::CThreadBase::create(LPTHREAD_START_ROUTINE lpStartAddress, void *lpParameter)
{
    close();
    int nRet = pthread_create(&m_thread, NULL, lpStartAddress, (void *)lpParameter);
    return nRet == 0;
}

void qcutil::CThreadBase::close()
{
    if(m_thread != 0)
        pthread_detach(m_thread);
    m_thread = 0;
}

bool qcutil::CThreadBase::terminate()
{
    if(m_thread == 0)
        return false;
    pthread_cancel(m_thread);
    close();
    return true;
}

bool qcutil::CThreadBase::alive()
{
    if(m_thread == 0)
        return false;
    int n = pthread_kill(m_thread, 0);
    if(n == ESRCH || n == EINVAL)
        return false;
    return true;
}

void qcutil::CThreadBase::join()
{
    pthread_join(m_thread, NULL);
}

void qcutil::CThreadBase::waitToEndKill(unsigned int waitTime)
{
    if(m_thread == 0)
        return;
    // 以20毫秒为单位，之前这里是以1毫秒为单位，太短了不合适。
    unsigned int loop_cnt = waitTime/20;
    if (loop_cnt == 0)
        loop_cnt = 1;
    for(unsigned int i = 0; i<loop_cnt;i++)
    {
        if(alive() == false)
        {
            close();
            return;
        }
        else
            qcutil::Time::sleepMilliSeconds(20);
    }
    if(alive())
        terminate();
    close();
}
